package database;

import java.util.Iterator;

/*
 *  A class offering access methods for a database of cats
 *  along with the number of tins of cat food they eat 
 */
public class Database  {

    private Dictionary<String, Integer> dictionary;

    // Constructs a new Database for use by the Cattery.
    public Database(Dictionary<String,Integer> dictionary) {
    	this.dictionary = dictionary;
    }

    /*
     * If the named cat is not present in the database, adds a fresh entry,
     * in the correct place, with the given name and number of tins.
     * Otherwise, that existing cat has its tins changed to the given value.
     */
    public void add(String name, int tins){
        dictionary.put(name, tins);
    }
    
    // Returns the total number of cats in the database.
    public int countCats() {
        return dictionary.size();
    }

    // Returns the total number of tins eaten each week by all the cats.
    public int countTins() {
        int res = 0;

        Iterator<DictionaryEntry<String,Integer>> iterator = dictionary.iterator();
        while(iterator.hasNext()){
            res += iterator.next().getValue(); 
        }
        return res;

    }

    /*
     * If the cat is present in the database, deletes it.
     * Otherwise leaves the database unchanged and prints
     * message.
     */
    public void delete(String name) {
        try{
            dictionary.remove(name);
        }catch(Exception e){
        	//leave the database unchanged
        	System.out.println(name + " not in database.");
        }
        
    }

    /*
     * If the cat is in the database, returns its weekly quota of tins.
     * Otherwise returns -1.
     */
    public int lookup(String name) {
    	try{
    		return dictionary.get(name);
    	}
    	catch(Exception e){
    		return -1;
    	}
    }

    /*
     * Displays contents of the database formatted <Name> [tab] <Tins>
     * (e.g., Tibbles   14), in alphabetical order of cats, one to a line.
     */
    public void printDatabase() {
        Iterator<DictionaryEntry<String,Integer>> iterator = dictionary.iterator();
        DictionaryEntry<String,Integer> tmp;
        while(iterator.hasNext()){
            tmp = iterator.next();
            System.out.println(tmp.getKey() + "\t" + tmp.getValue());
        }
    }

    // Removes all entries from the database.
    public void clear(){
    	dictionary.clear();
    }

    /*
     * Return the class name of the concrete ADT implementation.
     */
    protected String getDictionaryType(){
    	return dictionary.getClass().getSimpleName();
    }
}
